/**
 * @fileoverview   event/delegate  事件代理模块
 * @author 2kid
 * @version 0.1
 * Date: 12-1-31
 * Time: 下午2:26
 */
F.reg('event/delegate', function (f, event, dom) {
    var win = window, doc = win['document'], docElement = doc.documentElement;

    var fndelegate = {};
    /**
     * @name F.Event.delegate
     * @function
     * @namespace 代理事件
     * @param sel
     * @param condition
     * @param type
     * @param fn
     * @param ctx
     * @example
     * 例子：
     * 1.
     * //在document上添加一个事件处理程序，但是只有点击a标签才会触发，已节约资源
     * event.delegate('document','a'，'click',function(e){
     *     console.log(e);
     * });
     *
     */
    event.delegate = function (sel, condition, type, fn, ctx) {
        fndelegate[sel + condition] = createdelegate(sel, condition, fn, ctx);
        event.add(sel, type, fndelegate[sel + condition]);
    };
    /**
     * @name F.Event.undelegate
     * @function
     * @namespace 取消代理事件
     * @param sel
     * @param condition
     * @param type
     * @example
     * 例子：
     * 1.
     * event.undelegate('document','a'，'click');
     */
    event.undelegate = function (sel, condition, type) {
        event.del(sel, type, fndelegate[sel + condition]);
    };
    function createdelegate(sel, condition, fn, ctx) {
        return function (e) {
            if (findout(sel, e.target, condition)) {
                fn.call(ctx || win);
            }
        }
    }

    function findout(sel, ele, condition) {
        // div  a
        var iscur = false;
        dom.query(sel).find(condition).each(function (el) {
            if (el === ele) {
                iscur = true;
                return;
            }
        });
        return iscur;
    }

    return event;
}, {
    requires:[
        'event/handle',
        'dom'
    ]
});